/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * <p>Project: mp2022 - MpConfig
 * <p>Powered by webrx On 2022-04-15 16:30:55
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@Configuration
@MapperScan("cn.webrx.mapper")
@PropertySource("classpath:db.properties")
public class MpConfig {
    @Value("${db.driver:com.mysql.cj.jdbc.Driver}")
    private String driver;
    @Value("${db.url:jdbc:mysql://localhost:3306/oadb}")
    private String url;
    @Value("${db.username:root}")
    private String username;
    @Value("${db.password:}")
    private String password;

    @Bean(value = "ds",destroyMethod = "close") @Primary
    public HikariDataSource ds(){
        HikariDataSource ds = new HikariDataSource();
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setJdbcUrl(url);
        ds.setDriverClassName(driver);
        return ds;
    }

    @Bean("sf")
    public MybatisSqlSessionFactoryBean sf(HikariDataSource ds) throws IOException {
        var sf = new MybatisSqlSessionFactoryBean();
        sf.setDataSource(ds);
        GlobalConfig cfg = new GlobalConfig();
        cfg.setBanner(false);
        sf.setGlobalConfig(cfg);
        sf.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper*.xml"));
        return sf;
    }

}
